package com.example.mykotilin.paging

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.mykotilin.R
import com.example.mykotilin.databinding.ActivityPagingBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class PagingActivity : AppCompatActivity() {
    lateinit var binding: ActivityPagingBinding;
    private val viewModel by viewModels<CheeseViewModel> {
        CheeseViewModelFactor(application)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityPagingBinding.inflate(layoutInflater);
        setContentView(binding.root);

        val adapter = CheeseAdapter();//创建adapter
        binding.cheeseList.adapter = adapter; //设置adapter
        //刷新
        lifecycleScope.launch {
            viewModel.allCheeses.collectLatest { adapter.submitData(it) }
        }
        //增加点击事件
        initAddButtonListener();
        //初始化滑动删除
        initSwipeToDelete();
    }

    private fun initSwipeToDelete() {
        ItemTouchHelper(object : ItemTouchHelper.Callback() {
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
                val cheeseViewHolder = viewHolder as CheeseViewHolder
                return if (cheeseViewHolder.cheese != null) {
                    makeMovementFlags(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
                } else {
                    makeMovementFlags(0, 0)
                }
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean = false

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                (viewHolder as CheeseViewHolder).cheese?.let {
                    viewModel.remove(it) //从数据库删除，此时会自动更新
                }
            }

        }).attachToRecyclerView(binding.cheeseList)//连接到recyclerview
    }

    private fun initAddButtonListener() {
        binding.addButton.setOnClickListener {
            addCheese()
        }
    }

    private fun addCheese() {
        //进行添加
        val newCheese = binding.inputText.text.trim()
        if (newCheese.isNotEmpty()) {
            //插入新的名称
            viewModel.insert(newCheese)
            binding.inputText.setText("")
        }
    }
}